//
//  EditPanelInfoView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/7/25.
//

import UIKit
import RxSwift
import RxCocoa
class EditTankInfoView: GreenNaviBarView {
    lazy var disposeBag = DisposeBag()
    let tableView = EditTankTableView()
    var saveBtn = OperationButton(R.string.localizable.save(),enabled: true)
    lazy var addBtn: UIButton = {
        let view = UIButton()
        view.setImage(UIImage(named: "PVDDetail_systeminfo_add"), for: .normal)
        return view
    }()
    override func setUpView(){
        self.backgroundColor = .white
        //MARK: - addbtn
        self.addSubview(addBtn)
        addBtn.snp.makeConstraints { make in
            make.right.equalTo(-8)
            make.height.width.equalTo(40)
            make.centerY.equalTo(backToPreBtn)
        }
        let contentBackView = UIView()
        contentBackView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        self.addSubview(contentBackView)
        contentBackView.snp.makeConstraints { make in
            make.top.equalTo(topBackView.snp.bottom).offset(-20)
            make.left.right.bottom.equalToSuperview()
        }
        //
        contentBackView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.greaterThanOrEqualTo(0)
        }
        //
        contentBackView.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.bottom.equalTo(OperationButton.bottomMargin)
            make.left.right.equalTo(tableView)
            make.height.equalTo(48)
            make.top.equalTo(tableView.snp.bottom).offset(16)
        }
    }
    func setData(_ list: [InstallationDetailSystemDetailForHeaterModel]){
        self.addBtn.isHidden = list.count > 0 ? true : false//tank有且只有一条
        self.tableView.loadData(list)
        self.checkEverythingValid()
    }
    //MARK: - 必填项数据绑定控制saveBtn 是否可用
    private func checkEverythingValid(){
        let everythingValid = self.tableView.rx.observe(Array<InstallationDetailSystemDetailForHeaterModel>.self, "list").map({ list in
            var validFlag: Bool = true
            if let list = list {
                list.forEach { panelModel in
                    if panelModel.model == "" || panelModel.number_heaters == 0{
                        validFlag = false
                    }
                }
            }
            return validFlag
        }).share(replay: 1)
        //
        everythingValid.subscribe { [weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid {
                strongSelf.saveBtn.enableBtn()
            }else{
                strongSelf.saveBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
}
